//
//  NewsTableViewController.swift
//  xdjcy
//
//  Created by Henry on 15/12/7.
//  Copyright (c) 2015年 Henry. All rights reserved.
//

import UIKit

class NewsTableViewController: UITableViewController,SDCycleScrollViewDelegate,UISearchBarDelegate{
    
    @IBOutlet weak var imgSearch: UIImageView!
    @IBOutlet var imageCell: UITableViewCell!
    @IBOutlet var subCell: UITableViewCell?
    
    var date = NSDate()
    var templateName:String?
    var imgArray = NSMutableArray()
    var articleList = Array<ArticleModel>()
    var imageList = Array<ArticleModel>()
    var progress:MBProgressHUD!
    var url = ""
    var tabName = ""
    var refreshHeader:SDRefreshHeaderView!
    var refreshFooter:SDRefreshFooterView!
    
    var pageindex = 1
    
    required init!(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }
    
    override init!(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: "NewsTableViewController", bundle: nil)
    }
    
    override init(style: UITableViewStyle) {
        super.init(style: style)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //        imgArray = ["http://www.qqpk.cn/Article/UploadFiles/201407/20140711101445200.jpg","http://pic26.nipic.com/20121216/11622178_214926751152_2.jpg","http://pic29.nipic.com/20130527/12858576_115724447170_2.jpg","http://www.juzi2.com/uploads/allimg/130524/1_130524114402_1.jpg","http://tupian.qqjay.com/u/2013/0402/5_223819_1.jpg"]
        var tapgesture1  = UITapGestureRecognizer(target: self, action: "jumpSearch")
        imgSearch.userInteractionEnabled = true
        imgSearch.addGestureRecognizer(tapgesture1)
        
        getArticleList()
    }
    
    
    
    func jumpSearch()
    {
        var sb = UIStoryboard(name: "SearchBarStoryboard", bundle: nil)
        var vc = sb.instantiateViewControllerWithIdentifier("searchNavVC") as? UIViewController
        self.presentViewController(vc!, animated: false, completion: nil)
        
    }
    
    override func viewWillAppear(animated: Bool) {
        println("加载数据")
        println("加载的数据来源是:\(templateName)")
        
        refreshHeader = SDRefreshHeaderView()
        refreshHeader.addToScrollView(self.tableView)
        refreshHeader.addTarget(self, refreshAction: "getArticleList")
        refreshHeader.isEffectedByNavigationController = true
        refreshHeader.autoRefreshWhenViewDidAppear()
        setupFooter()
        
    }
    
    func getArticleList()
    {
        MenuTypeRN.sharedInstance.getArticlList(templateName!, did: { (result, message, imageResult, articleResult) -> Void in
            if result
            {
                self.imageList = imageResult
                self.articleList = articleResult
                self.tableView.reloadData()
            }
            self.refreshHeader.endRefreshing()
        })
    }
    
    func setupFooter()
    {
        refreshFooter = SDRefreshFooterView()
        refreshFooter.addToScrollView(self.tableView)
        refreshFooter.addTarget(self, refreshAction: "loadNextPage")
        
    }
    
    func loadNextPage()
    {
        pageindex = pageindex + 1
        var pagenumber = String(pageindex)
        MenuTypeRN.sharedInstance.getArticlePageList(templateName!, page: pagenumber) { (result, message, jsonResult) -> Void in
            if result
            {
                if jsonResult.count > 0
                {
                    for var i = 0; i < jsonResult.count; i++
                    {
                        self.articleList.append(jsonResult[i])
                    }
                    self.tableView.reloadData()
                    
                }
            }
            self.refreshFooter.endRefreshing()

        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return articleList.count + 1
        
    }
    
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let nib = NSBundle.mainBundle().loadNibNamed("SubTVC", owner: self, options: nil)
        
        if indexPath.row == 0
        {
            imgArray.removeAllObjects()
            for image in imageList
            {
                imgArray.addObject(BaseUrl + image.ImageHref!)
            }
            imageCell =  nib[1] as? UITableViewCell
            
            var cycleScrollView = SDCycleScrollView(frame: CGRectMake(0, 0, self.view.bounds.width, 180), imageURLStringsGroup: self.imgArray as [AnyObject])
            if imgArray.count == 1
            {
                cycleScrollView.autoScroll = false
            }
            cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight
            cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic
            
            cycleScrollView.autoScrollTimeInterval = 5
            
            cycleScrollView.delegate = self
            self.imageCell.addSubview(cycleScrollView)
            
            
            return imageCell
        }
        else
        {
            
            let cellId = "subCell"
            var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as?UITableViewCell
            
            if cell == nil
            {
                
                subCell = nib[0] as? UITableViewCell
                cell = subCell
            }
            var imageT = cell?.viewWithTag(1) as! UIImageView
            var title = cell?.viewWithTag(2) as! UILabel
            var jianjie = cell?.viewWithTag(3) as! UILabel
            var item = articleList[indexPath.row - 1]
            if item.ImageHref != ""
            {
                imageT.sd_setImageWithURL(NSURL(string: BaseUrl + item.ImageHref!), placeholderImage: imageT.image)
            }
            else
            {
                imageT.image = UIImage(named: "zwtp")
            }
            
            title.text = item.Title
            jianjie.text = item.Summary
            return cell!
        }
    }
    
    func cycleScrollView(cycleScrollView: SDCycleScrollView!, didSelectItemAtIndex index: Int) {
        println(index)
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == 0
        {
        }
        else
        {
            url = BaseUrl + "cmsArticleController.do?cmsArticleShow2&articleId=\(articleList[indexPath.row - 1].Id!)"
            
            tabName = articleList[indexPath.row - 1].Title!
            
            var sb = UIStoryboard(name: "Main", bundle: nil)
            var vc = sb.instantiateViewControllerWithIdentifier("webVC") as? WebViewViewController
            vc?.showUrl = url
            vc?.tabName = tabName
            self.navigationController?.pushViewController(vc!, animated: true)
        }
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0
        {
            return 180
        }
        else
        {
            return 100
        }
    }
    
    
    
    
    
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
    }
    */
    
    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
    // Delete the row from the data source
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */
    
    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    
    }
    */
    
    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
    }
    */
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */
    
}
